package com.example.chatgpt.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.chatgpt.LoginActivity;
import com.example.chatgpt.MyApplication;
import com.example.chatgpt.R;
import com.example.chatgpt.bean.ApiData;
import com.example.chatgpt.bean.User;
import com.example.chatgpt.dao.MessageDao;
import com.example.chatgpt.dao.UserDao;
import com.example.chatgpt.entity.UserInfo;
import com.example.chatgpt.util.CloseKeyBoardUtil;
import com.example.chatgpt.util.StatusBarUtil;

import java.util.List;


public class MeFragment extends Fragment implements View.OnClickListener {

    private TextView tv_hi_user;
    private MyApplication application;
    private User userInfo;
    private UserDao userDao;
    private MessageDao messageDao;
    private String user;
    private EditText updateUser;
    private EditText et_temperature;
    private EditText et_tokens;
    private ApiData apiData;

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        //获取user用户名 数据库 参数对象
        application = (MyApplication) getActivity().getApplication();
        userDao = application.getUserDao();
        messageDao = application.getMessageDao();
        userInfo = application.getUserInfo();
        user = userInfo.getUser();
        apiData = application.getApiData();

        //设置进入该fragment中状态栏的颜色
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            getActivity().getWindow().setStatusBarColor(Color.BLACK);
        }

        //设置该页面状态栏字体颜色为白色
        StatusBarUtil.setStatusBarTextColorWhite(getActivity());

        tv_hi_user = view.findViewById(R.id.tv_hi_user);
        tv_hi_user.setText(" Hi! " + user);
        //设置退出点击事件
        view.findViewById(R.id.tv_quit).setOnClickListener(this);
        //设置注销账户点击事件
        view.findViewById(R.id.tv_destroy_user).setOnClickListener(this);
        //设置修改密码点击事件
        view.findViewById(R.id.tv_update_password).setOnClickListener(this);
        //温度
        et_temperature = view.findViewById(R.id.et_temperature);
        //最大令牌数
        et_tokens = view.findViewById(R.id.et_tokens);
        //设置监听
        et_temperature.addTextChangedListener(new temperatureWatcher());
        et_tokens.addTextChangedListener(new tokenWatcher());
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_quit:
                jumpToLogin();
                break;
            case R.id.tv_destroy_user:
                userDao.deleteByUser(user);
                messageDao.deleteByUser(user);
                jumpToLogin();
                break;
            case R.id.tv_update_password:
                initUpdatePasswordDialog();
                break;
        }
    }

    //修改密码弹窗
    private void initUpdatePasswordDialog() {
        Dialog bottomDialog = new Dialog(getContext(), R.style.BottomDialog);
        //获取布局文件
        View view = LayoutInflater.from(getContext()).inflate(R.layout.update_password, null);
        //加入布局
        bottomDialog.setContentView(view);
        //设置参数
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels;
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
        //获取修改的账户名
        EditText updateUser = view.findViewById(R.id.et_update_user);
        //获取修改的密码
        EditText updatePass = view.findViewById(R.id.et_update_password);
        //获取确定修改的密码
        EditText confirmPass = view.findViewById(R.id.et_confirm_password);
        view.findViewById(R.id.btn_confirm_update).setOnClickListener(view1 -> {
            switch (view1.getId()) {
                case R.id.btn_confirm_update:
                    String mUpdateUser = updateUser.getText().toString();
                    String mUpdatePass = updatePass.getText().toString();
                    String mConfirmPass = confirmPass.getText().toString();
                    List<UserInfo> userInfos = userDao.queryByUser(mUpdateUser);
                    //先判断要修改密码的账户存不存在
                    if (!mUpdateUser.equals(user)) {
                        CloseKeyBoardUtil.hideOneInputMethod(getActivity(), view);
                        updateUser.requestFocus();
                        Toast.makeText(getContext(), "输入的用户名与该用户不同，请重新输入", Toast.LENGTH_SHORT).show();
                    } else {
                        //如果存在账户 判断修改的密码和确认修改的密码是否一样
                        if (mUpdatePass.equals(mConfirmPass)) {
                            //判断修改的密码是否和原密码一样
                            if (!mUpdatePass.equals(userInfos.get(0).password)) {
                                userDao.updatePass(userInfos.get(0).user, mUpdatePass);
                                bottomDialog.dismiss();
                                Toast.makeText(getContext(), "密码已修改，请重新登录", Toast.LENGTH_SHORT).show();
                                jumpToLogin();
                            } else {
                                CloseKeyBoardUtil.hideOneInputMethod(getActivity(), view);
                                updatePass.requestFocus();
                                Toast.makeText(getContext(), "修改的密码不能与原密码相同，请重新输入", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            //如果两次密码输入不一样
                            CloseKeyBoardUtil.hideOneInputMethod(getActivity(), view);
                            updatePass.requestFocus();
                            Toast.makeText(getContext(), "两次密码不一致，请检查两次密码的输入是否相同", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        });
    }

    //跳转登陆界面
    private void jumpToLogin() {
        userInfo.setQuitFlag(1);
        Intent intent = new Intent(getContext(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    //监听温度文本编辑框
    private class temperatureWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String edit = editable.toString();
            Log.d("guaimiao", edit);
           float temperature = Float.parseFloat(edit);
            apiData.setTemperature(temperature);
        }
    }

    private class tokenWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            Log.d("guaimiao", editable.toString());
            int maxTokens = Integer.parseInt(editable.toString());
            apiData.setMaxTokens(maxTokens);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //页面销毁时重新设置状态栏颜色为白色 字体颜色为黑色
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        StatusBarUtil.setStatusBarTextColorBlack(getActivity());
    }
}